#!/usr/bin/env python
# --coding:utf-8--

from neo4j import GraphDatabase

class readonly_neo4jDBOP:
    """ 定义一个neo4j操作类 """
    def __init__(self, neo4j_conf):
        self.driver = GraphDatabase.driver(neo4j_conf["uri"], 
                                           auth=(neo4j_conf["user"], 
                                           neo4j_conf["password"]), 
                                           max_connection_lifetime=3600 * 24 * 30,
                                           keep_alive=True)

    def get_dependencies(self, pkg_name, version):
        """ 查询数据库返回某个版本python包的全部依赖项 """
        pkg_full_name = pkg_name + "@" + version
        query = (
            "match (p1:Package) -[r:depends_on_pkg]-> (p2:Package) "
            "where p1.ID=$pkg_full_name "
            "return p2.name, p2.version"
        )
        # query = (
        #     "match (p1:Pkg) -[depend:dependOn]-> (p2:Pkg) "
        #     "where p1.ID=$pkg_full_name "
        #     "return p2.name, p2.version"
        # )
        dps = []
        with self.driver.session() as session:
                with session.begin_transaction() as tx:
                    result = tx.run(query, pkg_full_name=pkg_full_name)
                    dps.extend([record["p2.name"], record["p2.version"]] for record in result)
                    tx.commit()
        self.driver.close()
        return dps